#include <muduo/net/TcpServer.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <string>
#include <unordered_map>


class DictServer{
public:
    DictServer(int port):_server(&_baseloop,muduo::net::InetAddress("0.0.0.0",port),"DictServer",muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&DictServer::onConnection,this,std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DictServer::onMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }
    void start()
    {
        _server.start();
        _baseloop.loop();
    }
private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected())
        {
            std::cout<<"connect success"<<std::endl;
        }
        else{
            std::cout<<"connect error"<<std::endl;
        }
    }
    void onMessage(const muduo::net::TcpConnectionPtr &conn,muduo::net::Buffer *buffer,muduo::Timestamp )
    {
        static std::unordered_map<std::string ,std::string> dict_map ={
            {"hello","你好"},
            {"world","世界"}
        };
        std::string  msg = buffer->retrieveAllAsString();
        std::string res;
        auto iter = dict_map.find(msg);
        if(iter !=dict_map.end())
        {
            res= iter->second;
        }
        else{
            res="未知单词";
        }
        conn->send(res);
    }
private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};


int main()
{
    DictServer server(9090);
    server.start();
    return 0;
}